/*
 * Copyright (C) 2011 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.ProductDetail;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.LazyloadListActivity;
import com.mol.market.common.widget.LoadingDrawable;

/**
 * 产品讨论页<br>
 * 用户可以对产品进行各种讨论，用以展示讨论列表。
 * 
 * @author andrew
 * @date 2011-3-22
 * 
 */
public class ProductCommentActivity extends LazyloadListActivity implements ApiRequestListener {

    private AppListAdapter mCommentAdapter;
    private ProductDetail mProduct;
    private int mTotalSize;
    private EditText mComment;
    private Button mSend;
    private boolean mIsPaused;

    @Override
    public boolean doInitView(Bundle savedInstanceState) {
        setContentView(R.layout.market_activity_comment_list);
        Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                Constants.DETAIL_CLICK_COMMENT);
        final Intent intent = getIntent();
        mProduct = (ProductDetail) intent.getSerializableExtra(Constants.EXTRA_PRDUCT_DETAIL);
        initViews();
        doLazyload();
        return true;
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();

        
        if (mIsPaused) {
            RelativeLayout ll = (RelativeLayout) findViewById(R.id.login);
            ll.setBackgroundResource(ThemeManager.getResource(mSession,
                    ThemeManager.KEY_ACTION_BAR_BG));
            mIsPaused = false;
        }
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        super.onPause();

        mIsPaused = true;
    }

    @Override
    public void doLazyload() {
        MarketAPI.getComments(this, this, mProduct.getPid(), getItemsPerPage(), getStartIndex());
    }


    @Override
    public AppListAdapter doInitListAdapter() {
        mCommentAdapter = new AppListAdapter(
                getApplicationContext(), 
                null,
                R.layout.market_list_item_comment, 
                new String[] { 
                    Constants.KEY_COMMENT_AUTHOR,
                    Constants.KEY_COMMENT_DATE, 
                    Constants.KEY_COMMENT_BODY }, 
                new int[] {
                    R.id.tv_author, 
                    R.id.tv_time, 
                    R.id.tv_comment });
        mCommentAdapter.setActivity(this);
        return mCommentAdapter;
    }

   

    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {

        if (isFinishing()) {
            return;
        }
        switch (method) {
        case MarketAPI.ACTION_GET_COMMENTS:

            if (obj instanceof HashMap) {
                HashMap<String, Object> result = (HashMap<String, Object>) obj;

                mTotalSize = (Integer) result.get(Constants.KEY_TOTAL_SIZE);

                if (mTotalSize > 0) {
                    // 成功获取评论列表
                    mCommentAdapter.addDataList((ArrayList<HashMap<String, Object>>) result
                            .get(Constants.KEY_COMMENT_LIST));
                } else {
                    // 暂无评论
                    HashMap<String, Object> noData = new HashMap<String, Object>();
                    noData.put(Constants.KEY_COMMENT_BODY, getString(R.string.hint_no_comments));
                    mCommentAdapter.addData(noData);
                }
                setLoadResult(true);
            }
            break;
        
        case MarketAPI.ACTION_ADD_COMMENT:
            mSend.setEnabled(true);
            addMyComment();
            mComment.setText("");
            InputMethodManager imm = 
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mComment.getWindowToken(), 0);
            Utils.makeEventToast(getApplicationContext(), (String) obj, false);
            break;
        }
    }
    
    @Override
    public void onError(int method, int statusCode) {
        switch (method) {
        case MarketAPI.ACTION_GET_COMMENTS:
            setLoadResult(false);
            Utils.makeEventToast(getApplicationContext(), getString(R.string.no_network), false);
            break;
        case MarketAPI.ACTION_ADD_COMMENT:
            mSend.setEnabled(true);
            handlePostError(statusCode);
            break;
        default:
            break;
        }
        Log.d("error", "status code " + statusCode);
    }

    /*
     * 显示我的评论信息
     */
    private void addMyComment() {
        String commentBody = mComment.getText().toString();
        HashMap<String, Object> comment = new HashMap<String, Object>();
        comment.put(Constants.KEY_COMMENT_BODY, commentBody);
        comment.put(Constants.KEY_COMMENT_AUTHOR, mSession.getUserName());
        comment.put(Constants.KEY_COMMENT_DATE, Utils.formatTime(System.currentTimeMillis()));

        if (mTotalSize <= 0) {
            // 第一条评论
            mCommentAdapter.clearData();
        }
        mCommentAdapter.insertData(comment);
    }
    
    @Override
    public void onClick(View v) {
        super.onClick(v);

        if (R.id.login == v.getId()) {
            // 登录
            Intent loginIntent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivityForResult(loginIntent, 0);
        } else if(R.id.ib_send == v.getId()) {
            String body = mComment.getText().toString();
            if (TextUtils.isEmpty(body)) {
                // 不能发表空内容
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.alert_post_not_null), false);
            } else {
                mSend.setEnabled(false);
                MarketAPI.addComment(getApplicationContext(), ProductCommentActivity.this,
                        mProduct.getPid(), body.trim());
                Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                        Constants.DETAIL_POST_COMMENT);
            }
        }
    }

    /*
     * 处理评论的异常信息
     */
    private void handlePostError(int statusCode) {
        switch (statusCode) {
        case 232:
            // 非法回复内容
            Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_unsafe_word),
                    false);
            break;
        case 225:
            // 没有对应的帖子
            Utils.makeEventToast(getApplicationContext(),
                    getString(R.string.alert_product_not_exist), false);
            break;
        case 233:
            // 帐号被禁言
            Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_user_forbidden),
                    false);
            break;
        default:
            // 网络问题
            Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_post_error),
                    false);
            break;
        }
    }

    @Override
    protected int getItemCount() {
        return mTotalSize;
    }

    /*
     * 初始化View 判断用户是否登录，并显示没有登录的提示信息
     */
    private void initViews() {

        RelativeLayout ll = (RelativeLayout) findViewById(R.id.login);
        ll.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_BG));
        ll.setOnClickListener(this);
        TextView info = (TextView) ll.findViewById(R.id.tv_info);
        info.setTextAppearance(getApplicationContext(), ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_FONT_M));
        
        FrameLayout mLoading = (FrameLayout) findViewById(R.id.loading);
        ProgressBar mProgress = (ProgressBar) mLoading.findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
        mProgress.setVisibility(View.VISIBLE);
        
        mList = (ListView) findViewById(android.R.id.list);
        mList.setEmptyView(mLoading);
        
        toogleCommentViewStatus();
    }
    
    /*
     * 切换登录和评论控件的状态
     */
    private void toogleCommentViewStatus() {
        
        if (mSession.isLogin()) {
            findViewById(R.id.login).setVisibility(View.INVISIBLE);
            LinearLayout ll = (LinearLayout) 
                (((ViewStub) findViewById(R.id.view_stub_product_comment)).inflate());
            ll.setBackgroundResource(ThemeManager.getResource(mSession,
                    ThemeManager.KEY_ACTION_BAR_BG));
            Button send = (Button) ll.findViewById(R.id.ib_send);
            send.setTextAppearance(getApplicationContext(),
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT));
            mComment = (EditText) findViewById(R.id.et_comment);
            mSend = (Button) findViewById(R.id.ib_send);
            mSend.setTextAppearance(getApplicationContext(), ThemeManager.getResource(mSession,
                    ThemeManager.KEY_ACTION_BAR_FONT_M));
            mSend.setOnClickListener(this);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        toogleCommentViewStatus();
        super.onActivityResult(requestCode, resultCode, data);
    }
    

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCommentAdapter = null;
        mProduct = null;
        mComment = null;
        mSend = null;
      
    }
}